import React, { useState, useEffect } from 'react'
import { Tree, Input } from 'antd';
import { IconFont } from '../../../../components/IconFont';

const { Search } = Input;
/**
 * 
 * @param {Array} props data 树形数据
 * @param {Array} props expandedKeys （受控）展开指定的树节点
 * @param {Array} props selectedKeys （受控）设置选中的树节点
 * @param {String} props nodeTitle  标题字段，默认title
 * @param {String} props nodeChild  子级的字段，默认children
 * @param {Function(node, key, route)} props onSelect  点击树节点触发, 返回节点，key，展开路径
 * @param {Function(record)} props actionText  选中节点的自定义title
 */
export default function TreeSelect(props){
  const [data, setData] = useState([])
  const [expandedKeys, setExpandedKeys] = useState()
  const [selectedKeys, setSelectedKeys] = useState()
  const [dataList, setDataList] = useState([])
  const [autoExpandParent, setAutoExpandParent] = useState(false)
  const [selectedKeysAll, setSelectedKeysAll] = useState([])
  const nodeTitle = props.nodeTitle || 'title'
  const nodeChild = props.nodeChild || 'children'
  const actionText = props.actionText

  useEffect(() => {
    const list = generateList(props.data, undefined, dataList)
    setDataList(list)
  }, [props.data])

  // 初始化树形列表
  useEffect(() => {
    setData(dig(props.data, undefined, props.selectedKeys))
    setSelectedKeys(props.selectedKeys)
  }, [props.data, props.selectedKeys, selectedKeysAll])

  // 展开行受控
  useEffect(() => {
    setExpandedKeys(props.expandedKeys)
  }, [props.expandedKeys])

  const dig = (data, path, newSelectedKeys) => {
    const list = [];
    for (let i = 0; i < data.length; i++) {
      const key = path === undefined ? '' + i : `${path}-${i}`;
      const children = data[i][nodeChild]
      const treeNode = {
        title: <div style={selectedKeysAll.includes(key) ? { color: '#006eff' } : undefined}>{(actionText && newSelectedKeys[0] && key.toString() === (newSelectedKeys[0]).toString()) ? (actionText(data[i])) : data[i][nodeTitle]}</div>,
        key,
        switcherIcon: !children && <IconFont type='icondate-cur-active'></IconFont>
      };
  
      if (children && children.length > 0) {
        treeNode.children = dig(children, key, newSelectedKeys);
      }
      list.push(treeNode);
    }
    return list;
  }

  // 将数据平铺，便于搜索
  const generateList = (data, path, list) => {
    for (let i = 0; i < data.length; i++) {
      const key = path === undefined ? '' + i : `${path}-${i}`;
      const children = data[i][nodeChild]
      const treeNode = {
        title: data[i][nodeTitle],
        key,
      };
      list.push(treeNode);
      if (children && children.length > 0) {
        generateList(children, key, list);
      }
    }
    return list;
  };

  // 展开/收起节点时触发
  const onExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys)
    setAutoExpandParent(false)
  }

  // 点击树节点触发
  const onSelect = (selectedKeys) => {
    if (!selectedKeys[0]) return
    let info = getInfo(selectedKeys[0])
    if (props.onSelect) {
      // console.log(selectedKeys)
      props.onSelect(info.node, selectedKeys, info.route)
    } else {
      setExpandedKeys(info.route)
      setSelectedKeys(selectedKeys)
    }
  }

  // 获取当前选择节点的展开路径和节点信息
  const getInfo = (key) => {
    let arr = key.split('-')
    let node = props.data
    let route = []
    arr.forEach((item, index) => {
      node = (index === 0 ? node[item] : node[nodeChild][item])
      if (index < arr.length - 1) {
        let str = ''
        for (let i = 0; i < index + 1; i++) {
          str = !str ? str + arr[i] : str + '-' + arr[i]
        }
        route[index] = str
      }
    })
    return {
      node,
      route
    }
  }

  // 搜索
  const onSearch = (value) => {
    if (!value) {
      setSelectedKeysAll([])
      setExpandedKeys(['0'])
    } else {
      const selectedKeysAll = []
      const expandedKeys = dataList.map(item => {
        if (item.title.indexOf(value) > -1) {
          selectedKeysAll.push(item.key)
          return getParentKey(item.key)
        } else {
          return null
        }
      }).filter((item, i, self) => item && self.indexOf(item) === i)
      setSelectedKeysAll(selectedKeysAll)
      setExpandedKeys(expandedKeys)
      setAutoExpandParent(true)
    }
  }

  const getParentKey = (key) => {
    let arr = key.split('-')
    arr.splice(arr.length - 1, 1)
    return arr.join('-');
  };

  // 搜索遍历
  const ergodic = (data, value) => {
    let node = ''
    for (let i = 0; i < data.length; i++) {
      if (data[i].title === value) {
        node = data[i]
        break
      } else {
        if (data[i].children) {
          let res = ergodic(data[i].children, value)  
          if (res) {
            node = res
            break
          }
        }
      }
    }
    return node
  }  

  return (
    <div className="side_nav_containre" style={{ display: 'flex', flexDirection: 'column', height: 488 }}>
      <Search
        placeholder="请输入"
        onSearch={onSearch}
        style={{ width: '100%', margin: '10px 0', flexShrink: 0 }}
        allowClear
      />
      <div style={{ flexGrow: 1, overflow: 'auto' }}>
      <Tree
        showLine={true}
        onSelect={onSelect}
        treeData={data}
        expandedKeys={expandedKeys}
        selectedKeys={selectedKeys}
        onExpand={onExpand}
        autoExpandParent={autoExpandParent}
      />
      </div>
    </div>
  )
}